<template>
  <div class="scholarship-container">
    <div class="header">
      <div class="left">
        <h2>奖学金申请</h2>
      </div>
    </div>

    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="scholarships"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="项目名称" min-width="150" />
        <el-table-column prop="amount" label="金额" width="120">
          <template #default="{ row }">
            ¥{{ row.amount }}
          </template>
        </el-table-column>
        <el-table-column prop="quota" label="名额" width="100" />
        <el-table-column label="申请时间" width="300">
          <template #default="{ row }">
            {{ formatDate(row.startTime) }} 至 {{ formatDate(row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleApply(row)"
            >
              申请
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 申请对话框 -->
    <el-dialog
      title="奖学金申请"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="申请理由" prop="reason">
          <el-input
            v-model="form.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入申请理由"
          />
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
            class="upload-demo"
            action="http://localhost:9090/api/common/upload"
            :headers="uploadHeaders"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
          >
            <el-button type="primary">上传附件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持 jpg/png/pdf 文件，不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="submitting"
          @click="handleSubmit"
        >
          提交申请
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'StudentScholarshipList'
}
</script>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { getScholarships, submitApplication } from '@/api/student/scholarship'
import { formatDate } from '@/utils/format'
import { useStore } from 'vuex'

const store = useStore()

// 表格数据
const loading = ref(false)
const scholarships = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 获取奖学金列表
const fetchScholarships = async () => {
  try {
    loading.value = true
    const response = await getScholarships({
      page: currentPage.value - 1,
      size: pageSize.value
    })
    
    if (response) {
      scholarships.value = response.content
      total.value = response.totalElements
    }
  } catch (error) {
    console.error('Failed to fetch scholarships:', error)
    ElMessage.error('获取奖学金列表失败')
  } finally {
    loading.value = false
  }
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchScholarships()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchScholarships()
}

// 申请相关
const dialogVisible = ref(false)
const formRef = ref(null)
const submitting = ref(false)
const currentScholarship = ref(null)

const form = ref({
  reason: '',
  attachmentUrl: ''
})

const rules = {
  reason: [
    { required: true, message: '请输入申请理由', trigger: 'blur' },
    { min: 10, message: '申请理由不能少于10个字', trigger: 'blur' }
  ]
}

// 上传相关
const uploadHeaders = computed(() => ({
  Authorization: `Bearer ${store.state.token}`
}))

// 添加上传前验证
const beforeUpload = (file) => {
  const isValidType = ['image/jpeg', 'image/png', 'application/pdf'].includes(file.type)
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isValidType) {
    ElMessage.error('只能上传 JPG/PNG/PDF 格式的文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  return true
}

// 修改上传成功回调
const handleUploadSuccess = (response) => {
  if (typeof response === 'string') {
    form.value.attachmentUrl = response
  } else if (typeof response === 'object') {
    form.value.attachmentUrl = response.data || response.url || ''
  }
  ElMessage.success('上传成功')
}

const handleUploadError = () => {
  ElMessage.error('上传失败')
}

const handleApply = (row) => {
  currentScholarship.value = row
  form.value = {
    reason: '',
    attachmentUrl: ''
  }
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    const data = {
      scholarshipId: currentScholarship.value.id,
      ...form.value
    }
    
    await submitApplication(data)
    ElMessage.success('申请提交成功')
    dialogVisible.value = false
  } catch (error) {
    console.error('Submit failed:', error)
    ElMessage.error(error.response?.data || '提交失败')
  } finally {
    submitting.value = false
  }
}

// 在组件挂载时获取数据
onMounted(() => {
  fetchScholarships()
})
</script>

<style scoped>
.scholarship-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  padding: 16px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.left {
  display: flex;
  align-items: center;
  gap: 16px;

  h2 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #303133;
  }
}

.table-card {
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  padding: 16px 20px;
  display: flex;
  justify-content: flex-end;
  background-color: #fff;
  border-top: 1px solid #ebeef5;
}

/* 调整表格内容垂直对齐 */
:deep(.el-table .cell) {
  display: flex;
  align-items: center;
}

/* 优化按钮样式 */
:deep(.el-button--small) {
  padding: 8px 16px;
}

/* 上传组件样式 */
.upload-demo {
  :deep(.el-upload) {
    width: 100%;
  }
  
  :deep(.el-upload__tip) {
    line-height: 1.2;
    padding: 8px 0;
    color: #909399;
  }
}
</style> 